function [ para, yFit, rSqr, plateauValue ] = expFit_tau2( xData, yData, slope, xFit )
%% variant 1
% search for plateau phase
for idxPt = 2:length(yData)
    if(max(yData(1:idxPt)) - min(yData(1:idxPt))) >= 0.1*max(yData)
        break;
    end
end
fitStart = find(yData(1:idxPt-1) < median(yData(1:idxPt-1)),1,'last');
if isempty(fitStart)
    fitStart = 1;
end
% plateau
plateauValue_1 = median(yData(1:fitStart));
% exponential
para_1 = exp2fit(xData(fitStart:end),yData(fitStart:end),1);
% fit values & r²
y_1 = zeros(size(yData));
y_1(1:fitStart) = plateauValue_1;
y_1(fitStart:end) = para_1(1)+para_1(2)*exp(-xData(fitStart:end)/para_1(3));

yFit_1 = zeros(size(xFit));
yFit_1(xFit < xData(fitStart)) = plateauValue_1;
yFit_1(xFit >= xData(fitStart)) = para_1(1)+para_1(2)*exp(-xFit(xFit >= xData(fitStart))/para_1(3));
rSqr_1 = 1 - sum( ( yData - y_1 ).^2 ) / sum((yData - mean(yData)).^2);

%% variant 2
xDataCut = xData;
yDataCut = yData;

yDataFilt = medfilt1(yDataCut(1:end-2), 7);
if slope > 0
    [~,pklocs] = findpeaks(-yDataFilt);
    lastExtremumIdx = find(yDataFilt == min(yDataFilt), 1, 'last');
else
    [~,pklocs] = findpeaks(yDataFilt);
    lastExtremumIdx = find(yDataFilt == max(yDataFilt), 1, 'last');
end
if ~isempty(pklocs)
    if ~any(abs(pklocs - lastExtremumIdx) <= 2)
        lastExtremumIdx = min(pklocs(end),lastExtremumIdx);
    end
end
if length(xDataCut) > 6
    lastExtremumIdx = min(lastExtremumIdx,length(yDataCut)-5);
end
xDataCut = xDataCut(lastExtremumIdx:end);
yDataCut = yDataCut(lastExtremumIdx:end);
% plateau
plateauValue_2 = median(yDataCut(1:lastExtremumIdx));

para_2 = exp2fit(xDataCut,yDataCut,1);
y_2 = zeros(size(yData));
y_2(1:lastExtremumIdx) = plateauValue_2;
y_2(lastExtremumIdx:end) = para_2(1)+para_2(2)*exp(-xData(lastExtremumIdx:end)/para_2(3));

yFit_2 = para_2(1)+para_2(2)*exp(-xFit/para_2(3));
yFit_2(xFit < xData(lastExtremumIdx)) = plateauValue_2;
rSqr_2 = 1 - sum( ( yData - y_2 ).^2 ) / sum((yData - mean(yData)).^2);

%% decision
if rSqr_1 > rSqr_2
    para = para_1;
    yFit = yFit_1;
    rSqr = rSqr_1;
    plateauValue = plateauValue_1;
else
    para = para_2;
    yFit = yFit_2;
    rSqr = rSqr_2;
    plateauValue = plateauValue_2;
end
end